package com.iefgames.cs.comet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;

import com.iefgames.cs.framework.exception.CometDisconnectException;
import com.iefgames.cs.manager.CsManager;
import com.iefgames.cs.utils.JsonUtil;

public class CsComet extends AbstractComet {
	private static Log logger = LogFactory.getLog(CsComet.class);
	
	@Override
	public void comet(HttpServletRequest request, 
			HttpServletResponse response) throws CometDisconnectException {
		String csUuid = request.getParameter("uuid");
		if (csUuid == null
				|| csUuid.length() != 32
				|| StringUtils.EMPTY.equals(csUuid)) {
			//如果没有uuid则表示是第一次到来
			firstTime(request, response);
			return ;
		}
		
		Continuation continuation = ContinuationSupport.getContinuation(request, null);
		if (continuation.isNew()) {
			initComet(request, response);
			newComet(csUuid, continuation);
		}

		fire(request, response);
		
		sleep(continuation);
	}

	private void firstTime(HttpServletRequest request,
			HttpServletResponse response) {
		StringBuffer sb = new StringBuffer();
		sb.append(getHeadString());
		sb.append("<script type='text/javascript'>");
		sb.append("_('comet', '");
		sb.append(CsManager.getUuidBySessionId(request.getParameter("sessionId")));
		sb.append("');");
		sb.append("</script>");
		
		//构建标准html结构，和getHeadStering中的html标签配对
		sb.append("</body>");
		sb.append("</html>");
		
		PrintWriter writer = null;
		try {
			setNoCacheHeader(response);
			
			writer = response.getWriter();
			writer.println(sb.toString());
			writer.flush();
		} catch (IOException ioe) {
			//第一次comet不做任何处理
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
	
	@Override
	protected void initComet(HttpServletRequest request,
			HttpServletResponse response) {
		PrintWriter writer = null;
		try {
			setNoCacheHeader(response);
			
			writer = response.getWriter();
			writer.println(getHeadString());		//第一次真正comet时，把添加头部信息
			writer.flush();
		} catch (IOException ioe) {
			if (writer != null) {
				writer.close();
			}
			
			//comet 错误，表示登录之后又断开连接
			throw new CometDisconnectException(request, response, ioe);
		}
	}

	@Override
	protected String output(Vector shouts) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		sb.append("<script type='text/javascript'>");
		sb.append("_('msg', ");
		sb.append(JsonUtil.toJs(shouts));
		sb.append(");");
		sb.append("</script>");
		
		return sb.toString();
	}
}
